﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.hqApplication.Commands.Enterprisess
{
    /// <summary>
    /// 添加企业命令处理器
    /// </summary>
    public class AddEnterpriseHanler : IRequestHandler<AddEnterpriseCommand, Result>
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 企业仓储
        /// </summary>
        private readonly IBaseRepository<Enterprise> enterpriserepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">传值函数</param>
        /// <param name="enterpriserepository"></param>
        public AddEnterpriseHanler(IMapper mapper, IBaseRepository<Enterprise> enterpriserepository)
        {
            this.mapper = mapper;
            this.enterpriserepository = enterpriserepository;
        }
        /// <summary>
        /// 处理添加企业命令
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(AddEnterpriseCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Enterprise entity = mapper.Map<Enterprise>(request);
                var res = await enterpriserepository.Add(entity);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加企业成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加企业异常" + ex.Message;
            }
            return result;
        }

    }
}
